package com.domor.web.controller.app;

import com.domor.common.annotation.Log;
import com.domor.common.core.controller.BaseController;
import com.domor.common.core.domain.AjaxResult;
import com.domor.common.utils.ServletUtils;
import com.domor.common.utils.StringUtils;
import com.domor.framework.jwt.utils.JwtTokenUtil;
import com.domor.framework.shiro.service.SysPasswordService;
import com.domor.framework.shiro.util.ShiroUtils;
import com.domor.system.domain.SysRole;
import com.domor.system.domain.SysUser;
import com.domor.system.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Desc: app测试接口controller
 * @Author: liyuyang
 * @Date: 2020/6/31
 **/
@Slf4j
@Api(tags = "APP登录相关接口")
@RestController
@RequestMapping("app")
public class AppLoginController extends BaseController {

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysUserService userService;

    @PostMapping("/login")
    @ApiOperation("APP登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "帐号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String")
    })
    public AjaxResult<Map> appLogin(HttpServletResponse response, String username, String password) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, true);
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);

        SysUser user = ShiroUtils.getSysUser();
        SysRole role = user.getRoles().get(0);
        // 创建token
        String jwt = JwtTokenUtil.createJWT(username, role.getRoleKey(), user.getDeptId().intValue());
        log.info("### 登录成功, token={} ###", jwt);
        // 将token放在响应头
        response.setHeader(JwtTokenUtil.AUTH_HEADER_KEY, JwtTokenUtil.TOKEN_PREFIX + jwt);
        Map<String, Object> result = new HashMap<>();
        result.put("token", jwt);
        return success(result);
    }

    @GetMapping("/getInfo")
    @ApiOperation("APP个人信息")
    public AjaxResult<SysUser> getInfo(){
        String loginUserName = ServletUtils.getAttribute("loginUser");
        SysUser user = userService.selectUserByLoginName(loginUserName);
        return success(user);
    }

    @PostMapping("/updatePwd")
    @Log(title = "APP修改密码")
    @ApiOperation("APP修改密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "oldPassword", value = "旧密码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "newPassword", value = "新密码", required = true, dataType = "String")
    })
    public AjaxResult updatePwd(String oldPassword, String newPassword) {
        String username = ServletUtils.getAttribute("loginUser");
        SysUser user = userService.selectUserByLoginName(username);
        if (StringUtils.isNotEmpty(newPassword) && passwordService.matches(user, oldPassword)) {
            user.setSalt(ShiroUtils.randomSalt());
            user.setPassword(passwordService.encryptPassword(user.getLoginName(), newPassword, user.getSalt()));
            return toAjax(userService.resetUserPwd(user));
        } else {
            return error("修改密码失败，旧密码错误");
        }
    }

}
